﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace SCCN.Utility
{
    public static class EntityHelper
    {
        /// <summary>
        /// 集合转DataTable
        /// </summary>
        /// <param name="Entitys">泛型实体集合</param>
        /// <returns>DataTable数据表</returns>
        public static DataTable ListToDataTable<T>(this IEnumerable<T> Entitys)
        {
            DataTable dt = new DataTable();
            //创建属性的集合 
            List<PropertyInfo> pList = new List<PropertyInfo>();

            // 读取缓存中的反射实体类型及DataTable架构
            ReflectionCacheEntity obj = (ReflectionCacheEntity)CacheHelper.GetCache(typeof(T).GetType().ToString());
            if (obj == null)
            {
                obj = new ReflectionCacheEntity();
                obj.EntityType = typeof(T);
                obj.EntityPropertyinfos = obj.EntityType.GetProperties();
                //把所有的public属性加入到集合 并构建DataTable的Schema
                Array.ForEach<PropertyInfo>(obj.EntityPropertyinfos, p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
                obj.EntityTableSchema = dt;
                CacheHelper.SetCache(typeof(T).GetType().ToString(), obj, 20);
            }
            foreach (var item in Entitys)
            {
                //创建一个DataRow实例 
                DataRow row = dt.NewRow();
                //给row 赋值 
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
                //加入到DataTable 
                dt.Rows.Add(row);
            }
            return dt;
        }

    }

    /// <summary>
    /// 反射缓存实体
    /// </summary>
    public class ReflectionCacheEntity
    {
        public Type EntityType { get; set; }//实体类型
        public PropertyInfo[] EntityPropertyinfos { get; set; }//实体属性集合
        public DataTable EntityTableSchema { get; set; }//实体DataTable架构信息
    }

}
